package com.neusoft.edu.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

import reactor.core.publisher.Mono;
/**
 * 校验老师的口令
 * @author Zhang.Yan
 *
 */
@Component
public class TeaTokenGateWayFilterFactory extends AbstractGatewayFilterFactory<Object>
{
	

	@Override
	public String name()
	{
		return "TeaToken";
	}

	@Override
	public GatewayFilter apply(Object config)
	{
		 return (exchange, chain) -> {
	            //return chain.filter(exchange);
	            String token = exchange.getRequest().getQueryParams().getFirst("token");
	            //校验jwtToken的合法性
	            if (StringUtils.isNotBlank(token)) 
	            {
	                //合法
	                return chain.filter(exchange);
	            }


	            //不合法
	            ServerHttpResponse response = exchange.getResponse();
	            //设置headers
	            HttpHeaders httpHeaders = response.getHeaders();
	            httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
	            httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
	            //设置body
	            String result="{'code':0,'info':'非法登录，缺失口令','data':''}";
	            DataBuffer bodyDataBuffer = response.bufferFactory().wrap(result.getBytes());

	            return response.writeWith(Mono.just(bodyDataBuffer));
	        };
	}
	
	
	
}
